package com.manager.devicemanager.service.impl;

import com.manager.devicemanager.service.SystemSpaceService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统空间服务接口的实现类，使用 java.nio.file.FileStore 获取系统可用空间信息
 */
@Service
public class SystemSpaceServiceImpl implements SystemSpaceService {

    @Override
    public Map<String, Object> getSystemStorageInfo() throws IOException {
        // 用于存储总计空间信息
        Map<String, Object> storageInfo = new HashMap<>();
        long totalTotalSpace = 0;
        long totalUsableSpace = 0;

        // 遍历所有文件存储
        for (FileStore store : FileSystems.getDefault().getFileStores()) {
            // 获取总空间，单位为字节
            long totalSpace = store.getTotalSpace();
            // 获取可用空间，单位为字节
            long usableSpace = store.getUsableSpace();

            totalTotalSpace += totalSpace;
            totalUsableSpace += usableSpace;
        }

        // 计算已使用空间
        long usedSpace = totalTotalSpace - totalUsableSpace;
        // 计算使用百分比
        double usagePercentage = (totalTotalSpace == 0) ? 0 : (double) usedSpace / totalTotalSpace * 100;

        storageInfo.put("totalSpace", totalTotalSpace);
        storageInfo.put("usableSpace", totalUsableSpace);
        storageInfo.put("usedSpace", usedSpace);
        storageInfo.put("usagePercentage", usagePercentage);

        return storageInfo;
    }
}